#include <iostream>
#include <string>
#include <unistd.h>
#include <mysql/mysql.h>
using namespace std;
const string host = "127.0.0.1";
const string user = "tcy";
const string password = "12345678";
const string db = "conn";
unsigned int port = 3306;

int main()
{
    // printf("mysql client version:%s\n", mysql_get_client_info());
    // return 0;
    MYSQL *my = mysql_init(nullptr); // 初始化
    if (my == nullptr)
    {
        std::cerr << "init mysql failed" << std::endl;
        return 1;
    }
    // 连接mysql
    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << " mysql connect failed" << std::endl;
        return 2;
    }
    mysql_set_character_set(my, "utf8");
    // string sql = "update Student set name='唐模' where id = 3";
    // string sql = "insert into Student(name,age,id) values('汤姆',18,3)";
    string sql = "select * from Student";
    if (mysql_query(my, sql.c_str()))
    {
        cerr << sql << "failed" << endl;
        return 3;
    }
    else
        cout << sql << "success" << endl;
    // sleep(10);

    MYSQL_RES *res = mysql_store_result(my); // 获取查询结果集

    int row = mysql_num_rows(res);
    int field = mysql_num_fields(res);
    cout << "行:" << row << " 列:" << field << endl;

    // 获取属性
    MYSQL_FIELD *field_array = mysql_fetch_fields(res); // 获取所有列属性
    for (int i = 0; i < field; i++)
    {
        cout << field_array[i].name << "\t";
    }
    cout << "\n";
    // 获取内容
    for (int i = 0; i < row; i++)
    {
        MYSQL_ROW row_resule = mysql_fetch_row(res);
        for (int j = 0; j < field; j++)
        {
            cout << row_resule[j] << "\t";
        }
        cout << "\n";
    }
    // 释放结果集
    mysql_free_result(res);
    // 关闭链接
    mysql_close(my);
}